<template>
  <div>
    <el-form v-model="spuInfo" :label-position="'right'" :label-width="100">
      <el-form-item label="SPU名称" prop="name">
        <el-input
          v-model="spuInfo.spuName"
          placeholder="请输入SPU名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌" prop="tmId">
        <el-select v-model="spuInfo.tmId" placeholder="请选择SPU品牌">
          <el-option
            v-for="item in allTradeMarkList"
            :label="item.tmName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          type="textarea"
          v-model="spuInfo.description"
          placeholder="请输入SPU描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">
        <el-upload
          v-model:file-list="spuImageList"
          class="avatar-uploader"
          :action="`${VITE_APP_BASE_API}/admin/product/fileUpload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="imageBeforeUpload"
          :headers="uploadHeaders"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="imageDialogVisible">
          <img
            style="width: 100%; height: auto"
            :src="imageUrl"
            alt="Preview Image"
          />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="saleAttrIdName"
          style="width: 200px"
          :placeholder="
            unSelectSaleAttrList.length
              ? `还未选择${unSelectSaleAttrList.length}个属性`
              : `无`
          "
        >
          <el-option
            v-for="item in unSelectSaleAttrList"
            :label="item.name"
            :value="`${item.id}:${item.name}`"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          @click="addSaleAttr"
          :disabled="!saleAttrIdName"
          icon="plus"
          style="margin-left: 10px"
        >
          添加销售属性
        </el-button>
        <el-table :data="spuSaleAttrList" border style="margin: 10px 0">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            label="销售属性名称"
            width="120"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="销售属性值">
            <template #default="{ row }">
              <el-tag
                v-for="item in row.spuSaleAttrValueList"
                :key="item.id"
                style="margin: 10px 10px"
                closable
              >
                {{ item.saleAttrValueName }}
              </el-tag>
              <el-input
                v-model="row.saleAttrValue"
                v-if="row.flag"
                @blur="handleAttrValueBlur(row)"
                placeholder="请输入属性值"
                size="small"
                style="width: 100px"
              ></el-input>
              <el-button
                v-else
                icon="plus"
                @click="toEdit(row)"
                type="primary"
                size="small"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ $index }">
              <el-button
                type="danger"
                size="small"
                icon="delete"
                @click="spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="saveSPU"
          :disabled="!(spuSaleAttrList.length > 0)"
        >
          保存
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts" name="spuForm">
import {
  reqAddOrUpdateSpu,
  reqGetSpuImageList,
  reqGetSpuSaleAttrList,
  reqBaseSaleAttrList,
  reqAllBrand,
} from '@/api/product/spu/index.ts'
import { computed, ref } from 'vue'
import { type UploadUserFile, type UploadProps, ElMessage } from 'element-plus'
import type {
  SpuInfo,
  AllTradeMark,
  SpuImageResponseData,
  SpuSaleAttrResponseData,
  HasSaleAttrResponseData,
  HasSaleAttr,
  SpuSaleAttr,
} from '@/api/product/spu/type.ts'
import type { Trademark } from '@/api/product/trademark/type.ts'
import useUserStore from '@/store/modules/user.ts'
let userStore = useUserStore()
//spuInfo数据收集
const spuInfo = ref<SpuInfo>({
  id: '',
  spuName: '', //spu名称
  description: '', //spu描述
  category3Id: '', //三级分类id
  tmId: '', //品牌id
  spuSaleAttrList: [], //spu销售属性
  spuImageList: [], //spu图片
})
//spu图片处理==========
const VITE_APP_BASE_API = import.meta.env.VITE_APP_BASE_API
let imageDialogVisible = ref<boolean>(false)
let imageUrl = ref<string>('')
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  imageUrl.value = uploadFile.url!
  imageDialogVisible.value = true
}
const imageBeforeUpload = (file: any) => {
  console.log('file==', file)
  //可以自定义限制文件大小类型
}
const uploadHeaders = computed(() => ({
  Token: userStore.token,
}))
//所有品牌数据
let allTradeMarkList = ref<Trademark[]>([])
//所有销售属性数据
let allSaleAttrList = ref<HasSaleAttr[]>([])
//SPU图片数据
let spuImageList = ref<UploadUserFile[]>([])
// let spuImageList = ref<SpuImage[]>([])
//SPU销售属性数据
let spuSaleAttrList = ref<SpuSaleAttr[]>([])
//
let $emit = defineEmits(['changeScene'])
//取消
const cancel = () => {
  $emit('changeScene', { flag: 0, id: spuInfo.value.id })
}
const initAddData = async (c3Id: number | string) => {
  //清空数据
  spuInfo.value = {
    spuName: '', //spu名称
    description: '', //spu描述
    category3Id: c3Id, //三级分类id
    tmId: '', //品牌id
    spuSaleAttrList: [], //spu销售属性
    spuImageList: [], //spu图片
  }
  //清空图片数据
  spuImageList.value = []
  //清空销售属性数据
  spuSaleAttrList.value = []
  //清空收集的销售属性数据
  saleAttrIdName.value = ''
  //获取全部品牌
  const res: AllTradeMark = await reqAllBrand()
  console.log('AllTradeMark=', res)
  //获取全部销售属性
  const resAttr: HasSaleAttrResponseData = await reqBaseSaleAttrList()
  console.log('HasSaleAttrResponseData=', resAttr)
  allTradeMarkList.value = res.data
  allSaleAttrList.value = resAttr.data
}
//初始化SPU数据
const initSpuData = async (data: SpuInfo) => {
  spuInfo.value = data

  console.log('初始化数据', data)
  //获取全部品牌
  const res: AllTradeMark = await reqAllBrand()
  console.log('AllTradeMark=', res)
  //获取全部销售属性
  const resAttr: HasSaleAttrResponseData = await reqBaseSaleAttrList()
  console.log('HasSaleAttrResponseData=', resAttr)
  allTradeMarkList.value = res.data
  allSaleAttrList.value = resAttr.data
  //获取SPU下全部图片数据
  const resImage: SpuImageResponseData = await reqGetSpuImageList(
    data.id as number,
  )
  console.log('SpuImageResponseData=', resImage)
  //获取SPU下全部销售属性数据
  const resSaleAttr: SpuSaleAttrResponseData = await reqGetSpuSaleAttrList(
    data.id as number,
  )
  console.log('SpuSaleAttrResponseData=', resSaleAttr)

  //将数据赋值给响应式变量

  spuImageList.value = resImage.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  console.log('spuImageList==', spuImageList)
  spuSaleAttrList.value = resSaleAttr.data

  // spuInfo.value.spuImageList = spuImageList.value
  spuInfo.value.spuSaleAttrList = spuSaleAttrList.value
}
//计算当前spu未拥有的销售属性
let unSelectSaleAttrList = computed(() => {
  return allSaleAttrList.value.filter((item) => {
    return !spuSaleAttrList.value.some(
      (saleAttr) => saleAttr.baseSaleAttrId == item.id,
    )
  })
})
//收集选择的销售属性
let saleAttrIdName = ref<string>('')

//添加销售属性
const addSaleAttr = () => {
  spuSaleAttrList.value.push({
    baseSaleAttrId: Number(saleAttrIdName.value.split(':')[0]),
    saleAttrName: saleAttrIdName.value.split(':')[1],
    spuSaleAttrValueList: [],
  })
  //清空选择的销售属性saleAttrIdName
  saleAttrIdName.value = ''
}
//添加销售属性值
const toEdit = (row: SpuSaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}
//输入框blur
const handleAttrValueBlur = (row: SpuSaleAttr) => {
  row.flag = false
  //收集输入属性值
  const { saleAttrValue, baseSaleAttrId } = row
  //非法情况判断
  if (!saleAttrValue) {
    ElMessage.error('属性值不能为空')
    return
  }
  //判断是否存在相同属性值
  if (
    row.spuSaleAttrValueList.some(
      (item) => item.saleAttrValueName === saleAttrValue,
    )
  ) {
    ElMessage.error('属性值不能重复')
    return
  }
  row.spuSaleAttrValueList.push({
    saleAttrValueName: saleAttrValue,
    baseSaleAttrId,
  })
}
//保存Spu
const saveSPU = async () => {
  //整理收集的参数
  //照片参数收集
  spuInfo.value.spuImageList = spuImageList.value.map((img: any) => {
    return {
      imgName: img.name,
      imgUrl: img.response ? img.response.data : img.url,
    }
  })
  console.log('img====>', spuInfo.value.spuImageList)
  //销售属性参数收集
  spuInfo.value.spuSaleAttrList = spuSaleAttrList.value
  console.log('spuSaleAttrList====>', spuInfo.value.spuSaleAttrList)
  //添加或修改SPU
  let res = await reqAddOrUpdateSpu(spuInfo.value)
  if (res.code === 200) {
    ElMessage.success(spuInfo.value.id ? '更新成功' : '添加成功')

    $emit('changeScene', {
      flag: 0,
      id: spuInfo.value.id,
    })
  } else {
    ElMessage.error(spuInfo.value.id ? '更新失败' : '添加失败')
  }
}
defineExpose({ initSpuData, initAddData })
</script>
<style scoped lang="scss"></style>
